package com.kingyun.gpsinspection.purificationservice.services.iam.innerservice.adm.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.adm.MessageMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.adm.RelationMessageMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.jsm.EmployeeMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.Constant;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.adm.Message;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.adm.RelationMessage;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.Employee;
import com.kingyun.gpsinspection.purificationservice.facade.service.iam.IamFileService;
import com.kingyun.gpsinspection.purificationservice.facade.service.iam.adm.MessageService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @version V1.0
 * @Package com.cqhilink.iot.integratedapplicationmanagement.services.innerservice.adm.impl
 * @Description: ${TODO}(通告服务实现)
 * @author: lutianbo
 * @date: 2017/3/20,0020
 */

public class MessageServiceImpl implements MessageService{
    @Autowired
    private MessageMapper  messageMapper;
    @Autowired
    private RelationMessageMapper relationMessageMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private IamFileService iamFileService;
    /**
     *
     * @param messageId 主键id
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int deleteByPrimaryKey(String[] messageId)
    {
        if(messageId.length > 0){
            return  messageMapper.deleteByPrimaryKey(messageId);
        }
        return 0;
    }

    /**
     *
     * @param record
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int insertSelective(Message record,String uploadFiles,String deletedFiles){
        // 默认返回信息
        int resultCount=0;

        List<Employee> employeeList = null;
        RelationMessage relationMessage = new RelationMessage();
        List<RelationMessage> relationMessageList = new ArrayList<>();

        if(null != record){
            // 分解组织id
            String[] orgIds = record.getOrgIds().split(",");
            // 根据组织id查询人员
            if(orgIds.length>0){
                employeeList = employeeMapper.queryEmpIdByOrgIds(orgIds);
            }
            // 封装关联数据
            if(employeeList != null ){
                for(int i=0;i<employeeList.size();i++){
                    // 设置主键id
                    relationMessage.setRelationMessageId(UniqueUtil.uuid());
                    // 设置人员id
                    relationMessage.setEmployeeId(employeeList.get(i).getEmployeeId());
                    // 设置通告id
                    relationMessage.setMessageId(record.getMessageId());
                    // 设置是否已查看
                    relationMessage.setStatus(Constant.DEFAULT);
                    relationMessageList.add(relationMessage);
                }
            }
            // 保存通告信息
            resultCount += messageMapper.insertSelective(record);
            if(relationMessageList.size() > 0){
                //保存通告关联人员信息
                resultCount += relationMessageMapper.batchInserts(relationMessageList);
            }
            // 保存附件
            resultCount += iamFileService.newInsertFile(uploadFiles,deletedFiles,record.getMessageId());
        }
        return resultCount;
    }

    /**
     *
     * @param record
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int newInsertSelective(Message record,String uploadFiles,String deletedFiles,String empIds){
        // 默认返回信息
        int resultCount=0;

        List<Employee> employeeList = null;
        RelationMessage relationMessage = new RelationMessage();
        List<RelationMessage> relationMessageList = new ArrayList<>();

        if(null != record){
            // 保存通告信息
            resultCount += messageMapper.insertSelective(record);
            // 保存附件
            resultCount += iamFileService.newInsertFile(uploadFiles,deletedFiles,record.getMessageId());

            if(StringUtils.isBlank(empIds)){
                return resultCount;
            }
            // 人员数组
            String[] ids = empIds.split(",");

            // 封装关联数据
            if(ids != null ){
                for(int i=0;i< ids.length;i++){
                    // 设置主键id
                    relationMessage.setRelationMessageId(UniqueUtil.uuid());
                    // 设置人员id
                    relationMessage.setEmployeeId(ids[i]);
                    // 设置通告id
                    relationMessage.setMessageId(record.getMessageId());
                    // 设置是否已查看
                    relationMessage.setStatus(Constant.DEFAULT);
                    relationMessageList.add(relationMessage);
                }
            }
            if(relationMessageList.size() > 0){
                //保存通告关联人员信息
                resultCount += relationMessageMapper.batchInserts(relationMessageList);
            }

        }
        return resultCount;
    }

    /**
     * 根据主键查询信息
     * @param message
     * @return
     */
    @Override
    public Message selectByPrimaryKey(Message message)
    {
        if(null != message){
            return messageMapper.selectByPrimaryKey(message);
        }
        return null;
    }

    /**
     * 更新信息
     * @param record
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int updateByPrimaryKeySelective(Message record,String uploadFiles,String deletedFiles){
        // 默认返回信息
        int resultCount=0;
        List<Employee> employeeList = null;
        RelationMessage relationMessage = new RelationMessage();
        if(null != record){
            // 分解组织id
            String[] orgIds = record.getOrgIds().split(",");
            // 根据组织id查询人员
            if(orgIds.length>0){
                employeeList = employeeMapper.queryEmpIdByOrgIds(orgIds);
            }
            // 查询已关联人员
            List<RelationMessage> reList =  relationMessageMapper.selectPersonsByMessageId(record.getMessageId());

            // 老成员
            List<RelationMessage> oldRelationMessage = new ArrayList<>();

            // 新成员
            List<RelationMessage> newRM = new ArrayList<>();
            if(employeeList != null ){
                for (int i = 0; i <= employeeList.size(); i++){
                    Employee employee = employeeList.get(i);
                    RelationMessage rm = null;
                    for (int j = 0; j <= reList.size(); j++){
                        rm = reList.get(i);
                        // 区分人员
                        if (employee.getEmployeeId().equals(rm.getEmployeeId())){
                            break;
                        }
                    }
                    if (rm != null){
                        // old数据
                        oldRelationMessage.add(rm);
                    } else{
                        // new 数据
                        // 设置主键id
                        relationMessage.setRelationMessageId(UniqueUtil.uuid());
                        // 设置人员id
                        relationMessage.setEmployeeId(employeeList.get(i).getEmployeeId());
                        // 设置通告id
                        relationMessage.setMessageId(record.getMessageId());
                        // 设置是否已查看
                        relationMessage.setStatus(Constant.DEFAULT);
                        newRM.add(relationMessage);
                    }
                }
            }
            // 删除部分信息
            relationMessageMapper.dels(oldRelationMessage);
            // 保存通告信息
            resultCount += messageMapper.updateByPrimaryKeySelective(record);

            if(newRM.size() > 0){
                //保存通告关联人员信息
                resultCount += relationMessageMapper.batchInserts(newRM);
            }
            // 保存附件
            resultCount += iamFileService.newInsertFile(uploadFiles,deletedFiles,record.getMessageId());
        }
        return  resultCount;
    }

    @Override
    public int newUpdateByPrimaryKeySelective(Message record, String uploadFiles, String deletedFiles, String empIds){
        // 默认返回信息
        int resultCount=0;
        RelationMessage relationMessage = new RelationMessage();
        if(null != record){
            // 保存通告信息
            resultCount += messageMapper.updateByPrimaryKeySelective(record);
            // 保存附件
            resultCount += iamFileService.newInsertFile(uploadFiles,deletedFiles,record.getMessageId());

            if(StringUtils.isBlank(empIds)){
                return resultCount;
            }
            // 人员数组
            String[] ids = empIds.split(",");
            // 查询已关联人员
            List<RelationMessage> reList =  relationMessageMapper.selectPersonsByMessageId(record.getMessageId());
            // 老成员
            List<RelationMessage> oldRelationMessage = new ArrayList<>();
            // 新成员
            List<RelationMessage> newRM = new ArrayList<>();

            for (int i = 0; i < ids.length; i++){
                RelationMessage rm = null;
                for (int j = 0; j < reList.size(); j++){
                    rm = reList.get(j);
                    // 区分人员
                    if (ids[i].equals(rm.getEmployeeId())){
                        break;
                    }
                }
                if (rm != null){
                    // old数据
                    oldRelationMessage.add(rm);
                } else{
                    // new 数据
                    // 设置主键id
                    relationMessage.setRelationMessageId(UniqueUtil.uuid());
                    // 设置人员id
                    relationMessage.setEmployeeId(ids[i]);
                    // 设置通告id
                    relationMessage.setMessageId(record.getMessageId());
                    // 设置是否已查看
                    relationMessage.setStatus(Constant.DEFAULT);
                    newRM.add(relationMessage);
                    oldRelationMessage.add(relationMessage);
                }
            }
            // 保存通告关联人员信息
            if(newRM.size() > 0){
                resultCount += relationMessageMapper.batchInserts(newRM);
            }
            // 删除不在此范围内的信息
            if(oldRelationMessage.size()>0){
                relationMessageMapper.dels(oldRelationMessage);
            }
        }
        return  resultCount;
    }

    @Override
    public JSONObject list(Message message)
    {
        JSONObject jsonObject = new JSONObject();
        // 分页设置
        message.setLimit(message.getLimit() == null ? Integer.valueOf(10) : message.getLimit());
        message.setOffset(message.getOffset() == null ? Integer.valueOf(0) : message.getOffset());
        // 总条数
        jsonObject.put("total", messageMapper.queryCount(message));
        List<Message> trainList = messageMapper.queryList(message);
        jsonObject.put("rows", JSON.toJSON(trainList));
        return jsonObject;
    }
}
